<template>
  <div class="timing">
    <el-row style="margin-bottom:10px;">
      <el-col :span="24">
        <el-form :inline="true" :model="formInline" class="demo-form-inline queryFrom">
          <el-form-item label="任务名称">
            <el-input v-model="formInline.dataModelName" clearable placeholder="请输入任务名称" />
          </el-form-item>
          <el-form-item>
            <el-button plain @click="getUserList"><Icon type="ios-search" />查询</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <!-- 按钮 -->
    <el-row style="margin-bottom:10px;">
      <el-col :span="24">
        <el-button type="primary" @click="addUser('add')"><Icon type="md-add" />创建HTTP接入</el-button>
        <el-button @click="testFun">测 试</el-button>
      </el-col>
    </el-row>
    <!-- 表格 -->
    <ykhttb
      ref="httbRef"
      width="350"
      :btn-is-show="btnIsShow"
      :table-col="tabUserList"
      :table-data="tableUserData"
      @getDataDetileInfo="getDataDetileInfo"
      @deleteSelectData="deleteSelectData"
      @refresh="getUserList"
    />
    <!-- 分页 -->
    <div style="text-align:right;margin-top:10px;">
      <el-pagination
        :current-page="page"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog :close-on-click-modal="false" :title="title" :width="width" :visible.sync="dialogTableVisible">
      <!-- 名称和路径必输 -->
      <el-form v-if="dialogTableVisible" ref="ruleForm" :model="ruleForm" :rules="rules" label-width="110px" class="demo-ruleForm autoClass">
        <el-form-item label="接入名称" prop="joinName">
          <el-input v-model="ruleForm['joinName']" :disabled="disFlag" clearable placeholder="" />
        </el-form-item>
        <el-form-item label="API接口地址" prop="apiAddress">
          <el-input v-model="ruleForm['apiAddress']" :disabled="disFlag" clearable placeholder="" />
        </el-form-item>
        <el-form-item label="请求类型" prop="requestType">
          <el-select v-model="ruleForm['requestType']">
            <el-option value="GET" label="GET" />
            <el-option value="POST" label="POST" />
          </el-select>
        </el-form-item>
        <el-form-item label="AppId" prop="appId">
          <el-input v-model="ruleForm['appId']" :disabled="disFlag" clearable placeholder="" />
        </el-form-item>
        <el-form-item label="AppKey" prop="appKey">
          <el-input v-model="ruleForm['appKey']" :disabled="disFlag" clearable placeholder="" />
        </el-form-item>

        <el-form-item label="指定结构" prop="structure">
          <el-input v-model="ruleForm['structure']" :disabled="disFlag" clearable placeholder="" />
        </el-form-item>
        <el-form-item label="表名" prop="tableName">
          <el-input v-model="ruleForm['tableName']" :disabled="disFlag" clearable placeholder="" />
        </el-form-item>
        <el-form-item label="Cron表达式" prop="cron">
          <!-- @focus="innerVisible=true" -->
          <el-select v-model="ruleForm['cron']">
            <el-option v-for="(item,index) in cronList" :key="index" :value="item.cron" :label="item.dispatchName" />
          </el-select>
        </el-form-item>
        <el-form-item label="模型" prop="modelId">
          <el-select v-model="ruleForm['modelId']" @change="setdataModelTypeName(ruleForm['modelId'])">
            <el-option v-for="(item,index) in moduleListOptions" :key="index" :value="item.id" :label="item.dataModelName" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="ruleForm['requestType']=='POST'" label="Body参数" prop="bodyData" style="width: 100%;">
          <vueJsonEditor v-model="ruleForm['bodyData']" :disabled="disFlag" @has-error="jsonchange" @json-change="jsonchange" />
          <p v-if="isDisable" style="color: red;">格式有误</p>
        </el-form-item>
      </el-form>

      <el-divider />
      <div style="padding: 10px 10px 0 0;width: 100%;max-height:220px;overflow-y: scroll;">
        <div v-for="(item,index) in gzListOptions" :key="index" class="autoClass" style="margin-bottom: 10px;">
          <div class="autoClass" style="flex-wrap: nowrap;width: 47%;">
            <label style="width:140px;text-align: right;padding-right: 20px;line-height: 35px;">规则字段</label>
            <el-select v-model="item.ruleField" :disabled="disFlag" clearable placeholder="请选择规则字段">
              <el-option
                v-for="(item,i) in options4"
                :key="i"
                :label="item.fieldName"
                :value="item.fieldName"
              />
            </el-select>
          </div>
          <div class="autoClass" style="flex-wrap: nowrap;width: 47%;">
            <label style="width:140px;text-align: right;padding-right: 20px;line-height: 35px;">质量规则</label>
            <el-select v-model="item.quality" :disabled="disFlag" clearable placeholder="请选择质量规则">
              <el-option
                v-for="(item,i) in options5"
                :key="i"
                :label="item.qualityRuleName"
                :value="item.id"
              />
            </el-select>
          </div>
          <div style="width: 6;margin-left: 10px;">
            <el-button v-if="index==0" type="primary" @click="addgzListOptions('add')"><i style="font-size: 12px;" class="el-icon-circle-plus-outline" /></el-button>
            <el-button v-else type="danger" @click="addgzListOptions(index)"> <i style="font-size: 12px;" class="el-icon-remove-outline" /> </el-button>
          </div>
        </div>
      </div>

      <div v-if="!disFlag" style="text-align: center;">
        <el-button type="primary" :disabled="isDisable" @click="submitForm('ruleForm')">确定</el-button>
        <el-button @click="resetForm('return')">返回</el-button>
      </div>
      <el-dialog
        width="40%"
        title="Cron表达式"
        :visible.sync="innerVisible"
        append-to-body
      >
        <crontag @fill="getValue" @hide="getValue('false')" />
      </el-dialog>
    </el-dialog>

    <!-- 测试 -->
    <el-dialog :close-on-click-modal="false" width="50%" :visible.sync="testdialogTableVisible">
      <div>
        <div>
          <el-form v-if="testdialogTableVisible" ref="ruleForm2" :model="ruleForm2" :rules="rules2" label-width="80px" class="demo-ruleForm autoClass2">
            <el-form-item label="请求类型" prop="method" style="width:25%;">
              <el-select v-model="ruleForm2['method']">
                <el-option value="GET" label="GET" />
                <el-option value="POST" label="POST" />
              </el-select>
            </el-form-item>
            <el-form-item label-width="0" prop="url" style="position: relative;width: 65%;">
              <el-input v-model="ruleForm2['url']" :disabled="disFlag" clearable placeholder="请输入请求地址" @change="changeUrl" />
              <div style="position:absolute;top:27px;font-size:10px;color:rgb(255, 30, 30);">格式说明：“http://”  + “ip:” + 端口”  + “接口地址”</div>
            </el-form-item>
            <el-form-item label="" prop="" label-width="0" style="width: 10%;">
              <div style="text-align: center;">
                <el-button size="mini" style="width: 100%;padding: 9px 0;" type="primary" @click="closetestdialogTableVisible">发送</el-button>
              </div>
            </el-form-item>
            <el-form-item label="body参数" prop="body" style="margin-top:6px;width: 100%;min-height: 80px;">
              <vueJsonEditor v-model="ruleForm2['body']" :disabled="disFlag" @has-error="jsonchange" @json-change="jsonchange" />
              <p v-if="isDisable" style="color: red;">格式有误</p>
            </el-form-item>

          </el-form>
        </div>
        <div class="vueJsonEditor">
          <div v-if="isShowJson">
            <json-view :data="codeInfo" />
          </div>
        </div>
      </div>
    </el-dialog>

    <el-dialog :close-on-click-modal="false" width="50%" :visible.sync="testdialogTableVisible2">
      <el-table
        :data="tableData"
        :header-cell-style="{ background: '#eef1f6', color: '#000' }"
        border
        style="width: 100%"
      >
        <el-table-column
          align="center"
          prop="id"
          label="运行日志ID"
        />
        <el-table-column
          align="center"
          prop="tables"
          label="目标表"
        />
        <el-table-column
          align="center"
          prop="logType"
          label="日志类型"
        />
        <el-table-column
          align="center"
          prop="createTime"
          label="日志时间"
        />
        <el-table-column
          align="center"
          prop="remark"
          label="日志消息"
        />
      </el-table>
      <div style="text-align:right;margin-top:10px;">
        <el-pagination
          :current-page="page2"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="size2"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total2"
          @size-change="loghandleSizeChange"
          @current-change="loghandleCurrentChange"
        />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { httpRequestpage, httpRequestsave, httpRequestdelete, apiInfosend, dataModeldatagetList,
  httpRequeststart, httpRequeststop, httpRequesttrigger, dispatchpage, httpRequestupdate, dataQualityrulegetList, tbQualityRunLogDataList
} from '@/api/zt/index'
import experiment from '@/mixins/experiment'
import vueJsonEditor from 'vue-json-editor'
import crontag from '@/views/components/vue-cron-master/Crontab/index.vue'
import { validURL } from '@/utils/validate'
import jsonView from 'vue-json-views'
export default {
  components: { vueJsonEditor, crontag, jsonView },
  mixins: [experiment],
  data() {
    return {
      selectId: '',
      total2: 0,
      size2: 10,
      page2: 1,
      tableData: [],
      testdialogTableVisible2: false,
      gzListOptions: [
        {
          'ruleField': '',
          'quality': ''
        }
      ],
      options5: [],
      isShowJson: false,
      bodyParm: null,
      moduleListOptions: [],
      jsonData: { name: 'dog', age: 2, hobby: { eat: { food: '狗粮', water: '冰可乐' }, sleep: { time: '白日梦' }}},
      cronList: [],
      innerVisible: false,
      innerBodyParm: false,
      codeInfo: {},
      width: '50%',
      ruleForm2: {
        url: '',
        method: 'GET',
        body: {}
      },
      testdialogTableVisible: false,
      btnIsShow: {
        operate: true,
        update: true,
        startAndEnd: true,
        detile: false,
        del: true
      },
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      title: '新增',
      rules: {
        joinName: [
          { required: true, message: '请输入接入名称', trigger: 'change' }
        ],
        apiAddress: [
          { required: true, message: '请输入API接口地址', trigger: 'change' }
        ],
        bodyData: [
          { required: true, message: '请输入Body参数', trigger: 'change' }
        ],
        requestType: [
          { required: true, message: '请选择请求类型', trigger: 'change' }
        ],
        structure: [
          { required: true, message: '请输入指定结构', trigger: 'change' }
        ],
        tableName: [
          { required: true, message: '请输入表名', trigger: 'change' }
        ],
        modelId: [
          { required: true, message: '请选择模型', trigger: 'change' }
        ]
      },
      rules2: {
        url: [
          { required: true, message: ' ', trigger: 'change' }
        ]
      },
      dialogTableVisible: false,
      ruleForm: {
        'apiAddress': '',
        'appId': '',
        'appKey': '',
        'bodyData': {},
        'createTime': '',
        'cron': '',
        'id': 0,
        'joinName': '',
        'modelId': 0,
        'modelName': '',
        'pageIndex': 0,
        'pageSize': 0,
        'requestType': '',
        'spare1': '',
        'spare2': '',
        'structure': '',
        'tableName': '',
        'updateTime': ''
      },
      userId: '',
      formInline: {
        'dataModelName': ''
      },
      tableUserData: [],
      tabUserList: [
        {
          key: 'joinName',
          title: '接入任务名称'
        },
        {
          key: 'apiAddress',
          title: 'API地址'
        },
        {
          key: 'requestType',
          title: '请求类型'
        },
        {
          key: 'appKey',
          title: 'appKey'
        },
        {
          key: 'bodyData',
          title: 'body参数'
        },
        {
          key: 'structure',
          title: '指定结构'
        },
        {
          key: 'tableName',
          title: '保存的表名'
        }
      ],
      nsList: [],
      total: 0,
      size: 10,
      page: 1
    }
  },
  created() {
    dispatchpage({
      'pageIndex': 1,
      'pageSize': 2000,
      'or_orderby_createTime': 'dsc',
      'sk_like_dispatchName': ''
    }).then(res => {
      this.cronList = res.data.records
    })
  },
  mounted() {
    dataQualityrulegetList({
      'pageIndex': 1,
      'pageSize': 1000,
      'qualityRuleName': ''
    }).then(res => {
      this.options5 = res.data.records
    })
    dataModeldatagetList({
      'pageIndex': 1,
      'dataModelName': '',
      'dataModelTypeId': '',
      'pageSize': 11111
    }).then(res => {
      this.moduleListOptions = res.data.records
    })
    this.$nextTick(() => {
      this.getUserList()
    })
  },
  methods: {
    loghandleCurrentChange(v) {
      this.page2 = v
      this.showMonitor(this.selectId, v, this.size2)
    },
    loghandleSizeChange(v) {
      this.size2 = v
      this.showMonitor(this.selectId, 1, v)
    },
    showMonitor(id, page = 1, size = 10) {
      this.selectId = id
      tbQualityRunLogDataList(id, page, size).then(res => {
        if (res.code == 200) {
          this.tableData = res.data.records
          this.total2 = res.data.total
          this.testdialogTableVisible2 = true
        }
      })
    },
    addgzListOptions(v) {
      if (v == 'add') {
        this.gzListOptions.push(
          {
            'ruleField': '',
            'quality': ''
          }
        )
      } else {
        this.gzListOptions.splice(v, 1)
      }
    },
    changeUrl() {
      if (!this.ruleForm2['url']) {
        this.codeInfo = {}
        this.isShowJson = false
      }
    },
    getFocus() {
      this.innerBodyParm = true
    },
    setdataModelTypeName(v) {
      if (v.length == 0) {
        this.options4 = []
      }

      this.moduleListOptions.forEach((item, index) => {
        if (item.id == v) {
          this.ruleForm['modelName'] = item.dataModelTypeName
          this.options4 = item.fields
        }
      })
    },
    executeFun(v, type) {
      if (type == 'start') {
        httpRequeststart({ jobId: v }).then(res => {
          if (res.code == 200) {
            this.getUserList()
            this.$message.success('已启动')
          } else {
            this.errorDialog(res.msg)
          }
        })
      } else if (type == 'stop') {
        httpRequeststop({ jobId: v }).then(res => {
          if (res.code == 200) {
            this.getUserList()
            this.$message.success('已停止')
          } else {
            this.errorDialog(res.msg)
          }
        })
      } else if (type == 'onec') {
        httpRequesttrigger({ jobId: v }).then(res => {
          if (res.code == 200) {
            this.getUserList()
            this.$message.success('执行成功！')
          } else {
            this.errorDialog(res.msg)
          }
        })
      }
    },
    closetestdialogTableVisible(v) {
      if (this.ruleForm2['url'].length == 0) {
        this.$message.error('请先填写请求地址')
        return
      } else {
        if (!validURL(this.ruleForm2['url'])) {
          this.$message.error('地址输入有误')
          return
        }
      }
      if (v != 'return') {
        apiInfosend(this.ruleForm2).then(res => {
          try {
            this.codeInfo = JSON.parse(res.msg)
          } catch (error) {
            this.codeInfo = {}
          }
          this.isShowJson = true
        })
        return
      }
    },
    resetRuleForm2() {

    },
    testFun() {
      this.codeInfo = {}
      this.ruleForm2 = {
        url: '',
        method: 'GET',
        body: {}
      }
      this.testdialogTableVisible = true
    },
    deleteSelectData(v) {
      httpRequestdelete([v.id]).then(res => {
        if (res.code == 200) {
          this.getUserList()
        } else {
          this.errorDialog(res.msg)
        }
      })
    },
    handleNodeClick(data) { },
    verifyRequired() {
      let flag = true
      this.nsList = []
      if (this.gzListOptions.length == 1) {
        if (!this.gzListOptions[0].quality && !this.gzListOptions[0].ruleField) {
          this.ruleForm.qualityRule = null
          flag = true
        } else if (this.gzListOptions[0].quality && this.gzListOptions[0].ruleField) {
          this.ruleForm.qualityRule = JSON.stringify(this.gzListOptions)
          flag = true
        } else {
          flag = false
          this.$message.error(`请把第1条规则信息填写完整`)
        }
      } else {
        this.gzListOptions.forEach((item, index) => {
          if ((!item.quality && item.ruleField) || (item.quality && !item.ruleField)) {
            flag = false
            this.$message.error(`请把第${index + 1}条规则信息填写完整`)
          } else if (item.quality && item.ruleField) {
            this.nsList.push({
              quality: item.quality,
              ruleField: item.ruleField
            })
          }
        })
        this.ruleForm.qualityRule = JSON.stringify(this.nsList)
      }
      return flag
    },
    updataList() {
      const p = JSON.parse(JSON.stringify(this.ruleForm))
      p['bodyData'] = JSON.stringify(p['bodyData'])

      // console.log('1111',p)
      // return
      httpRequestupdate(p).then(res => {
        if (res.code == 200) {
          this.getUserList()
        } else {
          this.errorDialog(res.msg)
        }
      })
    },
    commitFromData() {
      if (!this.verifyRequired()) {
        // 验证规则字段必填项start
        return
      }
      if (this.ruleForm.requestType == 'GET') {
        this.ruleForm['bodyData'] = ''
      }
      if (this.title != '新增') {
        this.updataList()
        return
      }
      //     console.log('222',this.ruleForm)
      // return
      httpRequestsave(this.ruleForm).then(res => {
        if (res.code == 200) {
          this.getUserList()
        } else {
          this.errorDialog(res.msg)
        }
      })
    },
    handleSizeChange(v) {
      this.page = 1
      this.size = v
      this.getUserList()
    },
    handleCurrentChange(v) {
      this.page = v
      this.getUserList()
    },

    // 获取用户列表
    getUserList() {
      this.dialogTableVisible = false
      this.$refs.httbRef.isShowLoading(true)

      httpRequestpage({
        'pageIndex': this.page,
        'pageSize': this.size,
        'or_orderby_createTime': 'dsc',
        'sk_like_joinName': this.formInline.dataModelName
      }).then(res => {
        this.tableUserData = res.data.records
        this.total = res.data.total
        this.$refs.httbRef.isShowLoading(false)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  @import "~@/assets/styles/auto.scss";
  >>>.json-view-container {
    // background-color: #1e1e1e !important;
}
  .vueJsonEditor{
    border-radius: 4px;
    overflow:scroll;
    max-height:320px;
    border:1px solid #dcdfe6;
    margin-left: 80px;
    max-height: 200px;
    min-height: 150px;
    pointer-events: none;
  }
.addPs{
  display: flex;
  flex-direction: row;
  margin-bottom: 10px;
  >div{
    width:50%
  }
  span{
    display: inline-block;
    width: 10%;
  }
}
.autoClass{
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  .el-form-item{
    width:50%;
  }
}
.autoClass2{
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  .el-form-item{
    width:50%;
  }
}
.addcs{
  display: flex;
  flex-direction: row;
  margin-bottom: 10px;
}
.addcs2 .el-select {
  display: inline-block;
  width: 240px;
}
.autoInput{
  display: inline-block;
  width: 70%;
}
.infoTitle{
  border-bottom:1px solid #e5e5e5;
  margin-bottom: 30px;
  position: relative;
}
.infoTitle>span{
  position: absolute;
  left: 20px;
  background: #fff;
  width:80px;
  top:-15px;
  height:30px;
  text-align: center;
  line-height: 30px;
}
  .el-select{
      width:100%;
  }
  .timing{
    background:#fff;
    padding:20px;
  }
</style>
